/**
 * Created by tangting on 2017/12/5.
 */

import Vue from 'vue';
import tpl from './tpl.html';

import commonService from '../../../common/commonService';
import symbolConfig from '../../../common/symbolConfig';
import format from '../../../common/format';
import CONFIG from './config'

import Loading from '../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../grsc-base/component/NoData.vue';

import filter from '../../../../grsc-base/util/filter';
import mathtool from '../../../../grsc-base/util/mathtool';
import lang from './lang';

const SORT_UP = 'UP';
const SORT_DOWN = 'DOWN';

export default Vue.extend({
    name: "coins",
    template: tpl,
    components: {
        Loading,
        NoData
    },
    data() {
        return {
            symbolConfig: symbolConfig,

            lang: lang[this.$i18n.locale],
            isLoading: true,
            isActive: symbolConfig.MARKET_TABS.BTC.LABEL,
            filter: filter,
            keyCoin: '',

            coinsMap: {},   // 存储所有币子的映射关系，如{BTC_ACT: {}, BTC_LTC: {}...}
            currentCoins: [],

            currentBtcPrice: '--',
            currentEthPrice: '--',
            currentActPrice: '--',

            CONFIG: CONFIG,
            forkCoins: null,

            currentSortKey: 'changeRatio',  // 当前排序关键字，symbol, price, changeRatio, highPrice, lowPrice, cumulative, tradeFee
            currentSortOrder: SORT_DOWN,   // 升序还是降序，默认降序

            SORT_UP,
            SORT_DOWN,
            SORT_KEY: {
                symbol: 'symbol',
                price: 'price',
                changeRatio: 'changeRatio',
                highPrice: 'highPrice',
                lowPrice: 'lowPrice',
                cumulative: 'cumulative',
                tradeFee: 'tradeFee'
            }

        }
    },
    created() {
        let that = this;

        $.when(commonService.symbolList(),            // 币种的交易状态，上线、下线等
                commonService.symbolConfigList(),    // 交易手续费
                commonService.getBitfinexBtcPrice(),
                commonService.getTradeDetail()).done((symbolRep, symbolProfileRep, btcPriceRep, detailRep) => {

            if (symbolRep.code !== window.CODE.SUCCESS) {
                window.error(symbolRep.msg);
                return;
            }

            if (symbolProfileRep.code !== window.CODE.SUCCESS) {
                window.error(symbolProfileRep.msg);
                return;
            }

            if (btcPriceRep.code !== window.CODE.SUCCESS) {
                window.error(btcPriceRep.msg);
                return;
            }

            let symbolList = symbolRep.data;
            let symbolProfileList = symbolProfileRep.data;

            // 1.合并数组，并且初始化 this.coinsMap
            initCoinsMap(symbolList, symbolProfileList);

            // 将整合之后的数据提供给其他组件进行使用
            $(document).trigger('$$price', [this.coinsMap]);

            // 2.进行分区
            // doSymbolMarkets(temps);

            // 3. 获取BTC的价格
            doBtcRep(btcPriceRep);

            // 4. 展示价格
            doDetailRep(detailRep);

            // 5. 循环价格
            that._loopTradeDetail();

        });
        
        function initCoinsMap(symbolList, symbolProfileList) {
            let innerObj;

            $.map(symbolList, (item, index) => {

                for (let i = 0; i < symbolProfileList.length; i++) {
                    innerObj = symbolProfileList[i];

                    if (item.symbol === innerObj.symbol) {
                        item[innerObj.profileKey] = innerObj.profileValue;
                    }
                }
            });

            $.map(symbolList, (item, index) => {
                // item.SHOWSTATUS === 'ON'的选项
                if (item.SHOWSTATUS === 'ON') {
                    that.coinsMap[item.symbol] = item;
                }
            });

        }
        
        function doBtcRep(rep) {
            if (rep.code === window.CODE.SUCCESS) {
                that.currentBtcPrice = rep.data.last_price;
            }
            // console.log('that.currentBtcPrice:' + that.currentBtcPrice);
        }

        function doDetailRep(rep) {
            that._doResult(rep)
        }

    },
    mounted() {
        this.formatPrice('0.0000232');
    },
    methods: {

        goPage(item) {
            if( item.status !=='INIT'){
                window.location.href = './market.html?s=' + (item.assetCode2 + '_' + item.assetCode1);
            }
        },

        /**
         *
         * @param key
         */
        sortByKey(key) {
            // 新排序
            if (this.currentSortKey !== key) {
                this.currentSortKey = key;
                if (this.currentSortKey !== 'symbol') {
                    this.currentSortOrder = SORT_DOWN;  // 默认降序
                } else {
                    this.currentSortOrder = SORT_UP;
                }
            } else {
                if (this.currentSortOrder === SORT_UP) {
                    this.currentSortOrder = SORT_DOWN;
                } else {
                    this.currentSortOrder = SORT_UP;
                }
            }
            this._doCurrentCoins();
        },

        _resetSort() {
            this.currentSortKey = '';
            this.currentSortOrder = '';
        },

        /**
         * 处理目前需要展示的币种列表
         * @private
         */
        _doCurrentCoins() {
            let tempArr = [];
            let results = [];

            if (this.isActive !== symbolConfig.MARKET_TABS.USD.LABEL) {
                $.map(this.coinsMap, (item, key) => {
                    if (item.assetCode1 === this.isActive) {
                        tempArr.push(item);
                    }
                });
            } else {
                $.map(this.coinsMap, (item, key) => {
                    if (item.assetCode1 === 'USC' || item.assetCode1 === 'USDT') {
                        tempArr.push(item);
                    }
                });
            }


            // 进行排序

            let key = this.currentSortKey;
            if (key) {
                if (key === 'symbol') {
                    results = insertSortStr(tempArr, key, this.currentSortOrder);
                } else {
                    results = insertSortNum(tempArr, key, this.currentSortOrder);
                }
            } else {
                results = tempArr;
            }
            this.currentCoins = results;

            function insertSortNum(array, key, sortBy) {
                /*start根据已排列好的项数决定*/
                let start = 0;
                let num1;
                let num2;
                let len = array.length;
                /*按顺序，每一项检查已排列好的序列*/
                for (let i = start; i < len; start++, i++) {
                    /*跟已排好序的序列做对比，并插入到合适的位置*/
                    for (let j = 0; j < start; j++) {
                        num1 = parseFloat(array[i][key]);
                        num2 = parseFloat(array[j][key]);
                        /*小于或者等于时（我们是升序）插入到该项前面*/
                        if (num1 <= num2) {
                            // console.log(num1 + ' ' + num2);
                            array.splice(j, 0, array[i]);
                            /*删除原有项*/
                            array.splice(i + 1, 1);
                            break;
                        }
                    }

                }
                if (sortBy === SORT_DOWN) {
                    array.reverse();
                }
                return array;
            }

            function insertSortStr(array, key, sortBy) {
                /*start根据已排列好的项数决定*/
                let start = 0;
                /*按顺序，每一项检查已排列好的序列*/
                for (let i = start; i < array.length; start++, i++) {
                    /*跟已排好序的序列做对比，并插入到合适的位置*/
                    for (let j = 0; j < start; j++) {
                        /*小于或者等于时（我们是升序）插入到该项前面*/
                        if (array[i][key] <= array[j][key]) {
                            array.splice(j, 0, array[i]);
                            /*删除原有项*/
                            array.splice(i + 1, 1);
                            break;
                        }
                    }

                }
                if (sortBy === SORT_DOWN) {
                    array = array.reverse();
                }
                // log(array);
                return array;
            }

            function log(list) {
                $.map(list, (item, index) => {
                    console.log(JSON.stringify(item));
                });
            }

        },

        _doResult(rep) {
            this.isLoading = false;
            if (rep) {
                let arr = rep;
                if ($.isNumeric(this.currentBtcPrice) === true) {
                    this.currentEthPrice = rep['BTC_ETH'] && mathtool.multiplication(rep['BTC_ETH'].newPrice, this.currentBtcPrice);
                    this.currentActPrice = rep['BTC_ACT'] && mathtool.multiplication(rep['BTC_ACT'].newPrice, this.currentBtcPrice);
                }

                $.map(this.coinsMap, (item, key) => {
                    if (!arr.hasOwnProperty(item.symbol)) {
                        return;
                    }

                    let price;
                    item.price = filter.floorFixPrice(arr[item.symbol]['newPrice'], item[symbolConfig.PRICEPRECISION]);

                    if ($.isNumeric(this.currentBtcPrice)) {
                        if (key.split('_')[0] === 'BTC' && $.isNumeric(this.currentBtcPrice) === true) {
                            price = mathtool.multiplication(item.price, this.currentBtcPrice);
                        } else if (key.split('_')[0] === 'USC' || key.split('_')[0] === 'USDT') {
                            price = filter.floorFixPrice(item.price, 2);
                        } else if (key.split('_')[0] === 'ETH' && $.isNumeric(this.currentEthPrice) === true) {
                            price = mathtool.multiplication(item.price, this.currentEthPrice);
                        } else if (key.split('_')[0] === 'ACT' && $.isNumeric(this.currentActPrice) === true) {
                            price = mathtool.multiplication(item.price, this.currentActPrice);
                        }
                        item.priceUSD = filter.floorFixPrice(price, 2);
                        item.priceRMB = filter.floorFixPrice(mathtool.multiplication(price, this.CURRENCY_RMB), 2);
                    } else {
                        item.priceUSD = '--';
                        item.priceRMB = '--';
                    }

                    //最高价
                    item.highPrice = filter.floorFixPrice(arr[item.symbol]['24high'], item[symbolConfig.PRICEPRECISION]);

                    //最低价
                    item.lowPrice = filter.floorFixPrice(arr[item.symbol]['24low'], item[symbolConfig.PRICEPRECISION]);

                    //累计
                    item.cumulative = filter.floorFix(arr[item.symbol]['24Total'], item[symbolConfig.AMOUNTPRECISION]);


                    let pr_ne = arr[item.symbol]['newPrice']; // 最新價
                    let pr_op = arr[item.symbol]['24Price']; // 開盤價
                    // 漲跌幅
                    let distance = pr_ne - pr_op;
                    let symbol = '';
                    if (distance < 0) {
                        symbol = '-'
                    } else if (distance > 0) {
                        symbol = '+'
                    }

                    if (arr[item.symbol]['24Price'] == 0) {
                        item.changeRatio = filter.floorFix(0, 2);
                    } else {
                        item.changeRatio = symbol + filter.floorFix(filter.abs(distance) / pr_op * 100, 2);
                    }
                    item.changeRatioNum = parseFloat(item.changeRatio);
                });

                this._doCurrentCoins();

            }
        },
        fetchTradeFee() {
            commonService.getTradeFee({
                key: 'ASSETFEERATE'
            }).done(rep => {
                let arr;
                if (rep.code === window.CODE.SUCCESS) {
                    arr = rep.data;
                    $.map(arr, (item, index) => {
                        if (item.symbol === 'BTC_TIC') {
                            // this.coins['BTC_TV'].tradeFee = item.profileValue;
                            // this.coins['BTC_TV'].tradeFeeText = mathtool.multiplication(item.profileValue, 100);
                        } else {
                            if (this.coins[item.symbol]) {
                                this.coins[item.symbol].tradeFee = item.profileValue;
                                this.coins[item.symbol].tradeFeeText = mathtool.multiplication(item.profileValue, 100);
                            }
                        }
                    });
                }
            });
        },


        fetchTradeOpenStatus() {
            commonService.symbolList().done(rep => {
                let arr;
                if (rep.code === window.CODE.SUCCESS) {
                    arr = rep.data;
                    $.map(arr, (item, index) => {
                        if (item.symbol === 'BTC_TIC') {
                            // this.coins['BTC_TV'].status = item.status;
                        } else {
                            if (this.coins[item.symbol]) {
                                this.coins[item.symbol].status = item.status;
                            }
                        }
                    });
                }
            })
        },

        /**
         *
         * @param currentTab
         */
        changeTab(currentTab) {
            this.keyCoin = '';
            if (this.isActive !== currentTab) {
                this.isActive = currentTab;
                this._resetSort();
                // this._doCurrentCoins();
                this.sortByKey('changeRatio');
            }
        },

        _loopTradeDetail() {
            let that = this;
            commonService.onLoopGetTradeDetail(rep => {
                that._doResult(rep);
            });
        },

        /**
         * 从左往右第一个不为0的数开始置黑
         * @param money
         */
        formatPrice(money) {
            if ($.isNumeric(money) === false) {
                return money;
            }
            money = format.formatZeroSuffix(filter.floorFixPrice(money,8), 8);

            let i = 0;
            for( i=0;i<money.length;i++){
                if(money[i] !== '0'&&money[i] !== '.')
                    break;
            }
            let suffix = money.substring(0, i);
            let prefix = money.substring(i);
            // let index = money.indexOf('.');
            // let prefix = money.substring(0, index);
            // let suffix = money.substring(index + 1);
            return '<em class="em">' + suffix + '</em><span class="strong">' + prefix + '</span>';
        },
        /**
         * 整数部分置黑
         * @param money
         */
        formatMoney(money) {
            if ($.isNumeric(money) === false) {
                return money;
            }
            money = format.formatZeroSuffix(filter.floorFixPrice(money,8), 8);
            let index = money.indexOf('.');
            let prefix = money.substring(0, index);
            let suffix = money.substring(index + 1);
            return '<span class="strong">' + prefix + '. </span><em class="em">' + suffix + '</em>';
        }

    }
});
